"""统计看板服务."""

from __future__ import annotations

from datetime import datetime, timedelta
from typing import Any

from ..models.enums import LeadStage
from ..repositories.lead_repository import LeadRepository
from ..repositories.property_repository import PropertyRepository
from ..repositories.visitor_sheet_repository import VisitorSheetRepository


class StatsService:
    """统计看板业务逻辑."""

    def __init__(
        self,
        lead_repo: LeadRepository,
        property_repo: PropertyRepository,
        visitor_sheet_repo: VisitorSheetRepository,
    ) -> None:
        self.lead_repo = lead_repo
        self.property_repo = property_repo
        self.visitor_sheet_repo = visitor_sheet_repo

    def get_overview(self, owner_id: int | None = None) -> dict[str, Any]:
        """
        获取总览数据.

        Returns:
            - total_leads: 客户总数
            - new_this_week: 本周新增客户
            - conversion_rate: 转化率（成交/总数）
            - active_leads: 活跃客户（非已流失）
            - total_properties: 房源总数
            - monthly_visits: 本月带看次数
            - deals: 成交数量
        """
        # 客户总数
        total_leads = self.lead_repo.count_by_criteria(owner_id=owner_id)

        # 本周新增（从周一00:00开始）
        today = datetime.now().date()
        week_start_date = today - timedelta(days=today.weekday())
        week_start_datetime = datetime.combine(week_start_date, datetime.min.time())
        new_this_week_count = self.lead_repo.count_created_since(week_start_datetime, owner_id)

        # 转化率
        closed_won_count = self.lead_repo.count_by_criteria(
            stage=LeadStage.CLOSED_WON, owner_id=owner_id
        )
        conversion_rate = (closed_won_count / total_leads * 100) if total_leads > 0 else 0

        # 活跃客户（非已流失）
        closed_lost_count = self.lead_repo.count_by_criteria(
            stage=LeadStage.CLOSED_LOST, owner_id=owner_id
        )
        active_leads = total_leads - closed_lost_count

        # 房源总数
        total_properties = self.property_repo.count_by_criteria()

        # 本月带看次数
        current_month = datetime.now().month
        current_year = datetime.now().year
        monthly_visits = self.visitor_sheet_repo.get_monthly_stats(current_year, current_month)[
            "total_visits"
        ]

        return {
            "total_leads": total_leads,
            "new_this_week": new_this_week_count,
            "conversion_rate": round(conversion_rate, 2),
            "active_leads": active_leads,
            "closed_won": closed_won_count,
            "closed_lost": closed_lost_count,
            "total_properties": total_properties,
            "monthly_visits": monthly_visits,
        }

    def get_source_chart(self, owner_id: int | None = None) -> dict[str, int]:
        """获取来源渠道分布（饼图数据）."""
        return self.lead_repo.get_channel_stats(owner_id)

    def get_stage_funnel(self, owner_id: int | None = None) -> dict[str, int]:
        """获取阶段漏斗图数据."""
        return self.lead_repo.get_stage_stats(owner_id)

    # 保留向后兼容方法
    def channel_breakdown(self, owner_id: int) -> dict[str, int]:
        return self.get_source_chart(owner_id)

    def stage_breakdown(self, owner_id: int) -> dict[str, int]:
        return self.get_stage_funnel(owner_id)
